package model

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	ormlog "gorm.io/gorm/logger"
	"log"
	"os"
	"seckill-system/util"
	"time"
)

var (
	dblog ormlog.Interface
)


func init() {
	fout, err := os.OpenFile(util.ProjectRootPath+"/logs/mysql.log", os.O_CREATE, 0o644)
	if err != nil {
		panic(fmt.Errorf("打开【logs/mysql.log】文件失败: %v", err))
	}
	dblog = ormlog.New(
		log.New(fout, "\r\n", log.LstdFlags),
		ormlog.Config{
			SlowThreshold:             10 * time.Millisecond, //慢 SQL 阈值
			IgnoreRecordNotFoundError: false,
			LogLevel:                  ormlog.Silent,
			Colorful:                  false, 		//彩色打印
		})
}

func InitDB() *gorm.DB {
	dbViper:=util.CreateConfig("mysql")
	dbViper.WatchConfig()
	dsn:=dbViper.GetString("mysql.dsn")
	if dsn=="" {
		panic(fmt.Errorf("解析mysql配置文件错误"))
	}
	db, err:=gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:dblog,
		PrepareStmt:true,
	})
	if err!=nil {
		util.LogRus.Panicf("connect to mysql use dsn %s failed: %v", dsn, err)
		panic(err)
	}
	sqlDB, err:=db.DB()
	if err!=nil{
		util.LogRus.Panicf("initial db.DB() failed: %v", err)
		panic(err)
	}
	sqlDB.SetMaxIdleConns(20)
	sqlDB.SetMaxOpenConns(100)
	err = initTables(db)
	if err!=nil{
		util.LogRus.Panicf("create table error: %v", err)
		panic(err)
	}
	return db
}

func initTables(db *gorm.DB) error {
	return db.AutoMigrate(&Gift{}, &Inventory{}, &Order{})
}
